package com.fone.player.activity.pay;

import java.net.URLEncoder;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.app.sdk.AliPay;
import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.pay.PayResultDialog.AlPayResltListener;
import com.fone.player.billing.IFonePayManager;
import com.fone.player.billing.bean.AlParasBean;
import com.fone.player.billing.bean.VIPProtocBean;
import com.fone.player.billing.foneali.Result;
import com.fone.player.billing.foneali.Rsa;
import com.fone.player.billing.impl.FonePayManager;
import com.fone.player.billing.util.FoneConstants;
import com.fone.player.billing.util.common.PayEngine;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.constant.FoneConstant;
import com.fone.player.entity.Download;
import com.fone.player.sns.UserInfoManager;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.view.WeixinDownloadDialog;
import com.fone.player.widget.pay.MyWebView;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class FoneThirdPayActivity extends BaseActivity implements
		IWXAPIEventHandler, OnClickListener {
	private static final String TAG = "FoneThirdPayActivity";
	private IWXAPI mWxApi;
	public static boolean show_dialog2;
	private TextView mTitleTv;
	private Button mRightBt, mPayTitle;
	private TextView mLoadingText;
	private MyWebView mWebView;
	private LinearLayout mLoading;
	private IntentFilter intentFilter;
	private BroadcastReceiver loginSuccessBr;
	private static Handler mHandler = null;
	private boolean isDoingFee, isAliFee, isFirstLoading, isFirstRedirect,isFirstQuery;
	private boolean url_goback, ali_success;
	private String mFeeUrl, mPayFrom, mLoginFrom, mNotifyUrl, mNotifyPr,
			mAliSId, mclid; //mNotifyUrl 上报url  mNotifyPr 价格  mAliSId 订单号
	private ArrayList<String> mUsers;
	private int mPayType;
	private int PAY_FOR_VIP = 1;
	private int PAY_FOR_CHARGE = 2;
	private IFonePayManager mFonePayManger;
	private PayResultDialog payResultDialog;
	private AlPayResltListenerImp alPayResltListener;
	private boolean isWxPay;
	private boolean isSuccess;// 是否第一次加载易宝银联成功页面
	private boolean isPayError;// 是否第一次加载易宝银联成功页面
	private int isSuccessTimes = 0;
	private int backFlage = 0;

	private static final int ALI_PAY_RESULT = 1;
	private static final int WX_PAY_RESULT = 2;
	private static final int USER_LOGIN = 3;
	private static final int CANCELLODING = 4;
	private static final int GET_THIRD_PAY_PAGE = 5;
	private static final int GET_USER_VIP_STATE = 6;
	private static final int NOTIFY_ALI_PAY = 7;
	private static final int GET_ALI_PAY_INFO = 8;
	private static final int GET_WX_PAY_INFO = 9;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fone_pay);
		// registerNetworkStatePeceiver();
		initLoginSuccessReceiver();
		initView();
		initHandler();
		initData();
	}

	private void initHandler() {
		// TODO 初始化handler
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case WX_PAY_RESULT:
					break;
				case USER_LOGIN:
					cancelLoading();
					backFlage = 1;
					isAliFee = false;
					Result result = new Result((String) msg.obj);
					L.i(TAG, "ali result" + result.getResult());
					L.i(TAG, "ali resultCode" + result.getResultCode());
					String notifyUrl;
					// result.get
					if (null != result && "9000".equals(result.getResultCode())) {
					} else {
						// isCancleFee = true;
						alPayResltListener = new AlPayResltListenerImp();
						payResultDialog = new PayResultDialog(mContext,
								alPayResltListener);
						payResultDialog.showPopWindow(mWebView,
								result.getResult());
						String errorinfo = PayEngine.getEncodeInfo(result
								.getResult());
						notifyUrl = PayEngine.getNotifyUrl(mNotifyUrl,
								errorinfo, 1, mNotifyPr, mAliSId);
						L.i(TAG, "支付宝客户端上报地址：" + notifyUrl);
						// PayEngine.getNotifyInfo(notifyUrl, null,
						// PayEngine.GET);
						notifyFeeServer(notifyUrl);
					}
					break;
				case ALI_PAY_RESULT:
					cancelLoading();
					Result aliresult = new Result((String) msg.obj);
					L.i(TAG, "ali result" + aliresult.getResult());
					String alinotifyUrl;
					if (null != aliresult
							&& "9000".equals(aliresult.getResultCode())) {
						if (mPayType == PAY_FOR_VIP) {
							UserInfoManager.saveVipType("1");
						}
						alPayResltListener = new AlPayResltListenerImp();
						payResultDialog = new PayResultDialog(mContext,
								alPayResltListener);
						payResultDialog.showPopWindow(mWebView, "支付成功");
						ali_success = true;
						String errorinfo = PayEngine.getEncodeInfo(aliresult
								.getResult());
						alinotifyUrl = PayEngine.getNotifyUrl(mNotifyUrl,
								errorinfo, 0, mNotifyPr, mAliSId);
						L.i(TAG, "支付宝客户端上报地址：" + alinotifyUrl);
						notifyFeeServer(alinotifyUrl);

					}
					// else{
					// isCancleFee = true;
					// alPayResltListener = new AlPayResltListenerImp();
					// payResultDialog = new PayResultDialog(mContext,
					// alPayResltListener);
					// payResultDialog.showPopWindow(mWebView,
					// aliresult.getResult());
					// String errorinfo =
					// PayEngine.getEncodeInfo(aliresult.getResult());
					// alinotifyUrl = PayEngine.getNotifyUrl(mNotifyUrl,
					// errorinfo, 1,mNotifyPr,mAliSId);
					// L.i(TAG, "支付宝客户端上报地址："+alinotifyUrl);
					// // PayEngine.getNotifyInfo(notifyUrl, null,
					// PayEngine.GET);
					// notifyFeeServer(alinotifyUrl);
					// }
					break;
				case CANCELLODING:
					cancelLoading();
					break;
				case GET_THIRD_PAY_PAGE:
					mPayTitle.setText(R.string.tobe_vip_title);
					VIPProtocBean vipProtocBean = (VIPProtocBean) msg.obj;
					if (null != vipProtocBean) {
						if (FoneConstants.FEE_PAGE_WEBVIEW.equals(vipProtocBean
								.getType()) && null != vipProtocBean.getRqUrl()) {
							// 加载webView页面
							loadUrl(vipProtocBean.getRqUrl());
						}
						// else
						// if(FoneConstants.FEE_PAGE_XML.equals(vipProtocBean.getType())
						// && null !=vipProtocBean.getRqUrl()){
						// L.i(TAG, "登录成功到sp计费页面");
						// mFonePayManger.startSPPay(mPayType, mPayFrom,
						// vipProtocBean.getRqUrl());
						// Activity currentActivity = ActivityQueue.popIndex(0);
						// currentActivity.finish();
						// }
						else {
							FoneUtil.showToast(getApplicationContext(),
									R.string.retry_network_error);
							L.i(TAG,
									"获取页面加载形式错误 或者rqurl错误》》"
											+ vipProtocBean.getType());
						}

					} else {
						FoneUtil.showToast(getApplicationContext(),
								R.string.retry_network_error);
						L.i(TAG, "请求计费中心取包月策略失败 ");
					}

					break;
				case GET_USER_VIP_STATE:
					L.i(TAG, "获取用户订购状态结束:" + UserInfoManager.isVip());
					L.i(TAG, "返回码:" + backFlage);
					finish();
					break;
				case NOTIFY_ALI_PAY:
					break;
				case GET_ALI_PAY_INFO:
					AlParasBean alParasBean = (AlParasBean) msg.obj;
					goToAliPay(alParasBean);
					break;
				case GET_WX_PAY_INFO:
					PayReq wxPayInfo = (PayReq) msg.obj;
					goWxPay(wxPayInfo);

					break;
				default:
					break;
				}
			}

			private void goToAliPay(AlParasBean alParasBean) {
				L.i(TAG, "backFlage" + backFlage);
				if (null == alParasBean) {
					Toast.makeText(mContext, R.string.retry_network_error,
							Toast.LENGTH_LONG).show();
				} else {
					mNotifyUrl = alParasBean.getRurl();
					mNotifyPr = alParasBean.getTof();
					mAliSId = alParasBean.getSid();
					StringBuilder sb = new StringBuilder();
					sb.append("partner=\"");
					sb.append(alParasBean.getPtner());
					sb.append("\"&out_trade_no=\"");
					sb.append(alParasBean.getSid());
					sb.append("\"&subject=\"");
					sb.append(alParasBean.getSj());
					sb.append("\"&body=\"");
					sb.append(alParasBean.getBd());
					sb.append("\"&total_fee=\"");
					sb.append(alParasBean.getTof());
					// sb.append("0.01");
					sb.append("\"&notify_url=\"");

					// 网址需要做URL编码
					sb.append(URLEncoder.encode(alParasBean.getNurl()));
					sb.append("\"&service=\"mobile.securitypay.pay");
					sb.append("\"&_input_charset=\"UTF-8");
					sb.append("\"&return_url=\"");
					// sb.append(URLEncoder.encode(alParasBean.getRurl()));
					sb.append(URLEncoder.encode(alParasBean.getNurl()
							+ "&type=1"));
					sb.append("\"&payment_type=\"1");
					sb.append("\"&seller_id=\"");
					sb.append(alParasBean.getSel());

					// 如果show_url值为空，可不传
					// sb.append("\"&show_url=\"");
					sb.append("\"&it_b_pay=\"1m");
					sb.append("\"");
					String aliPayInfo = new String(sb);
					L.i(TAG, "加密前info = " + aliPayInfo);
					String sign = Rsa.sign(aliPayInfo, alParasBean.getPrik());
					// boolean doCheck = Rsa.doCheck(aliPayInfo, sign,
					// Keys.PUBLIC);
					// if(doCheck){
					// L.i(TAG, "支付宝能够正常解密》》》"+doCheck);
					// }
					if (null != sign && !"".equals(sign)) {
						sign = URLEncoder.encode(sign);
						aliPayInfo += "&sign=\"" + sign + "\"&" + getSignType();
						// start the pay.
						L.i(TAG, "加密后含sign info = " + aliPayInfo);

						final String orderInfo = aliPayInfo;
						new Thread() {
							@Override
							public void run() {
								if (backFlage == 0) {
									backFlage = -1;
									AliPay alipay = new AliPay(
											FoneThirdPayActivity.this, mHandler);
									Result r = null;
									// 设置为沙箱模式，不设置默认为线上环境
									// alipay.setSandBox(true);
									String result = alipay.pay(orderInfo);
									L.i(TAG, "result = " + result);
									if (null != result) {
										r = new Result(result);
									}
									Message msg = new Message();
									msg.what = USER_LOGIN;
									msg.obj = result;
									mHandler.sendMessage(msg);
									if (null != r
											&& (!(r.getResult().equals(
													"操作已经取消。")
													|| r.getResult().equals(
															"用户取消") || r
													.getResult().equals(
															"同一订单禁止同时多次支付。")))) {
										Message m = Message.obtain();
										m.what = ALI_PAY_RESULT;
										m.obj = result;
										mHandler.sendMessage(m);
									}
								} else {
									L.i(TAG, "点击返回键 不在进行支付");
								}
							}
						}.start();
					} else {
						L.i(TAG, "sign签名出错，无法调用支付宝");
					}
				}
			}

			private void goWxPay(PayReq wxPayInfo) {
				if (null != wxPayInfo && !TextUtils.isEmpty(wxPayInfo.appId)) {
					L.i(TAG, "注册APP" + wxPayInfo.appId + ">>prepayid>>"
							+ wxPayInfo.prepayId);
					mWxApi = WXAPIFactory.createWXAPI(
							ApplicationManage.getGlobalContext(),
							wxPayInfo.appId);
					// mWxApi = WXAPIFactory.createWXAPI(this, wxPayInfo.appId);
					FoneConstants.app_ID = wxPayInfo.appId;
					// mWxApi.handleIntent(getIntent(), this);
					boolean isPaySupported = mWxApi.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
					boolean isWXInstall = mWxApi.isWXAppInstalled();
					if (isWXInstall && isPaySupported) {
						if (null != wxPayInfo && null != mWxApi) {
							// UrlConstants.FEE_NOTIFY_SERVER = wxPayInfo.();
							PayReq req = new PayReq();
							req.appId = wxPayInfo.appId;
							req.partnerId = wxPayInfo.partnerId;
							req.prepayId = wxPayInfo.prepayId;
							req.nonceStr = wxPayInfo.nonceStr;
							req.timeStamp = String.valueOf(wxPayInfo.timeStamp);
							req.packageValue = wxPayInfo.packageValue;
							L.i(TAG, "" + req.packageValue);
							req.sign = wxPayInfo.sign;
							boolean sendReq = mWxApi.sendReq(req);
							if (sendReq) {
								L.i(TAG, "完成微信支付请求" + wxPayInfo.toString());
							}
						} else {
							L.i(TAG, "获取微信支付信息失败");
						}
					} else {
						cancelLoading();
						if (!isWXInstall) {
							
							new WeixinDownloadDialog(mContext, ActivityQueue.popIndex(0));
							L.i(TAG, "未安装微信");
							
//							Toast.makeText(mContext, R.string.uninstall_wx,
//									Toast.LENGTH_LONG).show();
						} else if (!isPaySupported) {
							L.i(TAG, "微信版本低 不支持微信支付");
							Toast.makeText(mContext, R.string.wx_version_check,
									Toast.LENGTH_LONG).show();
						}
					}
				} else {
					cancelLoading();
					Toast.makeText(mContext, R.string.retry_network_error,
							Toast.LENGTH_LONG).show();
					L.i(TAG, "注册APP失败");
				}
			}

		};

	}

	protected void notifyFeeServer(String notifyUrl) {
		L.i(TAG, "支付宝上报");
		PayEngine.getNotifyInfo(notifyUrl, null, PayEngine.GET);
		sendMessage(NOTIFY_ALI_PAY, null);
	}

	private void initData() {
		// TODO 初始化数据 计费类型：1 充值 2 购VIP
		Intent intent = getIntent();
		mPayType = intent.getIntExtra("type", -1);
		mLoginFrom = intent.getStringExtra("loginfrom");
		mPayFrom = intent.getStringExtra("payfrom");
		mFeeUrl = intent.getStringExtra("url");
		mclid = intent.getStringExtra("clid");
		mUsers = new ArrayList<String>();
		mUsers = intent.getStringArrayListExtra("userlist");
		mFonePayManger = FonePayManager.getInstance();
		if (mPayType == PAY_FOR_CHARGE) {
			// TODO 充值初始化逻辑
			mPayTitle.setText(R.string.pay_charge_title);
			if (UserInfoManager.isLogin()) {
				// TODO 已登录：走充值
				mFeeUrl = PayEngine.getChargeProUrl(mContext);
				mFeeUrl = PayEngine.formatFeeUrl(mContext, mPayFrom, mFeeUrl,
						mclid);
				// mFeeUrl = mFeeUrl+"&comefrom="+mPayFrom;
				L.i(TAG, "获取充值策略url" + mFeeUrl);
				loadingView();
				loadUrl(mFeeUrl);
			} else {
				L.i(TAG, "charge_unLogin:", UserInfoManager.isLogin());
				Toast.makeText(mContext, R.string.unlogin_error,
						Toast.LENGTH_SHORT).show();
				Activity activity = ActivityQueue.popIndex(0);
				FoneUtil.feeToLoginPage(activity, mLoginFrom, mPayFrom,
						mPayType, mUsers, mclid);
			}
		} else if (mPayType == PAY_FOR_VIP) {
			if (!(FoneConstants.FEE_FROM_BE_VIP.equals(mPayFrom) || FoneConstants.FEE_FROM_ACTIVITY
					.equals(mPayFrom))) {
				mPayTitle.setText(R.string.pay_vip_title);
				isDoingFee = true;
				String mVip_page = mFeeUrl + "&cipher="
						+ Request.getInstance().getCipher();
				loadUrl(mVip_page);
			} else {
				mPayTitle.setText(R.string.tobe_vip_title);
				// TODO 包月数据初始化逻辑 根据登录状态走不同分支 ：
				checkUserLoginState();
			}
		} else {
			L.i(TAG, "feeType error:", mPayType);
			backFromPay();
		}
	}

	private void checkUserLoginState() {
		if (UserInfoManager.isLogin()) {
			isDoingFee = false;
			// TODO　已登录： 请求vb策略 走计费
			L.i(TAG, "请求vb策略 走计费");
			L.i(TAG, "计费url login：" + mFeeUrl);
			getThirdPayVIP();

		} else {
			L.i(TAG, "未登录 到登录页面");
			loadingView();
			isDoingFee = false;
			Activity activity = ActivityQueue.popIndex(0);
			FoneUtil.feeToLoginPage(activity, mLoginFrom, mPayFrom, mPayType,
					mUsers, mclid);
		}
	}

	// private void AliPay() {
	// // TODO Auto-generated method stub
	// mFeeUrl = PayEngine.getAliPayUrl(mContext);
	// String aliPayInfo = PayEngine.getAliPayInfo(mFeeUrl, null,
	// PayEngine.GET);
	//
	// }
	private void wxPay(String url) {

		// mFeeUrl = PayEngine.getWxPayUrl(mContext);
		mFeeUrl = url + "&cipher=" + Request.getInstance().getFeeCipher();
		L.i(TAG, "计费中心下发微信计费策略" + url);
		new Thread(new Runnable() {
			@Override
			public void run() {
				L.i(TAG, "支付宝url" + mFeeUrl);
				PayReq wxPayInfo = PayEngine.getWxInfo(mFeeUrl, null,
						PayEngine.GET, mPayType);
				sendMessage(GET_WX_PAY_INFO, wxPayInfo);
			}
		}).start();

	}

	// 阿里支付相关————————————————————————————
	// 请求服务器获取加密签名后的 商品订单信息info
	private void aliPay(String url) {
		try {
			mFeeUrl = url + "&cipher=" + Request.getInstance().getFeeCipher();
			new Thread(new Runnable() {
				@Override
				public void run() {
					L.i(TAG, "支付宝" + mFeeUrl);
					AlParasBean alParasBean = PayEngine.getAliPayInfo(mFeeUrl,
							null, PayEngine.GET);
					sendMessage(GET_ALI_PAY_INFO, alParasBean);
				}
			}).start();

		} catch (Exception ex) {
			ex.printStackTrace();
			sendMessage(CANCELLODING, null);
			L.i(TAG, "支付宝信息获取失败 异常");
//			Toast.makeText(mContext, R.string.retry_network_error, Toast.LENGTH_LONG).show();
		}

	}

	private void initView() {
		// TODO 初始化数据
		mPayTitle = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_title_text_tv);
		mTitleTv.setVisibility(View.GONE);
		mRightBt.setVisibility(View.GONE);
		mLoading = (LinearLayout) findViewById(R.id.loading_pay);
		mLoadingText = (TextView) findViewById(R.id.tv_loading_pay_text);
		mPayTitle.setOnClickListener(this);
		initWebView();
	}

	private void initWebView() {
		mWebView = (MyWebView) findViewById(R.id.webView_pay);
		mWebView.setInitialScale(39);
		mWebView.requestFocus();
		WebSettings setting = mWebView.getSettings();
		setting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);// 自适应页面适配让网页自适应屏幕宽度
		setting.setJavaScriptCanOpenWindowsAutomatically(true);
		setting.setAllowFileAccess(true);
		setting.setJavaScriptEnabled(true);
		setting.setSupportZoom(true);
		setting.setBuiltInZoomControls(false);

		WebViewClient mWebViewClient = new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO 加载页面需要根据逻辑走不同分支
				L.v(TAG, "shouldOverrideUrlLoading:", url);
				shouldLoadUrl(url);
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO 开始加载网页时调用
				L.i(TAG, "onPageStarted", ">>>" + url);
				mLoadingText.setText("1%");
				L.e(TAG, "WebView view, String url", url);
//				loadingResultTip(url);
				if(url.contains("/epayquery?")){
					isFirstQuery = true;
				}
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO 页面加载结束调用
				L.i(TAG, "onPageFinished", ">>>" + url);
				if (url.contains("ebp_gp") || isFirstLoading) {// ||
																// url.contains("payview")
					url_goback = true;
				} else if(isSuccess){
					isSuccessTimes++;
					L.i(TAG, "isSuccessTimes"+isSuccessTimes);
					if(isSuccessTimes == 3){
						cancelLoading();
						isSuccessTimes = 0;
					}
				}else {
					cancelLoading();
				}
				if (url.contains("payresult=1") || url.contains("/ebp_nr?")) {
					url_goback = false;
					mLoadingText.setText("支付结果");
					L.i(TAG, "支付完成后 改变标题" + url_goback + url);
				}
				loadingResultTip(url);
				L.v(TAG, "onPageFinished end url:", url);
				super.onPageFinished(view, url);
			}

			@Override
			public void onLoadResource(WebView view, String url) {
				if (url.contains("ebp_cap") || url.contains("request")
						|| url.contains("payview") || url.contains("paytypes")
						|| url.contains("bank")) {
					super.onLoadResource(view, url);
					url_goback = true;
				} else {
					// url_goback = false;
					super.onLoadResource(view, url);
				}
			}

			@Override
			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				handler.proceed();
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				L.v(TAG, "onReceivedError description:", description);
				L.v(TAG, "onReceivedError errorCode:", "" + errorCode);
				L.v(TAG, "onReceivedError end url:", failingUrl);
			}
		};

		mWebView.setWebViewClient(mWebViewClient);

		mWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				AlertDialog.Builder b = new AlertDialog.Builder(
						FoneThirdPayActivity.this);
				String[] messages = message.split("#");
				if (messages.length > 1) {
					b.setTitle(messages[0]);
					b.setMessage(messages[1]);
				} else {
					b.setTitle("提示");
					b.setMessage(messages[0]);
				}
				b.setPositiveButton("确定", new AlertDialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						result.confirm();
					}
				});
				b.setCancelable(false);
				b.create();
				b.show();
				return true;
			};

			@Override
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {

				AlertDialog.Builder b = new AlertDialog.Builder(
						FoneThirdPayActivity.this);
				b.setTitle("");
				b.setMessage(message);
				b.setPositiveButton("确定", new AlertDialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						result.confirm();

					}
				});
				b.setNegativeButton(R.string.app_name,// ??
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								result.cancel();

							}
						});
				b.setCancelable(false);
				b.create();
				b.show();
				return true;
			}

			@Override
			public boolean onJsTimeout() {
				return super.onJsTimeout();
			}

			@Override
			public void onProgressChanged(WebView view, int newProgress) {

				if (!isFirstLoading && !isSuccess) {
					if (newProgress > 95) {
						cancelLoading();
					} else {
						mLoadingText.setText(newProgress + "%");
					}
				}else if(isSuccess) {
					L.i(TAG, "newProgress",newProgress);
				}else {
					if (isFirstRedirect) {
						mLoadingText.setText("正在打开支付页面");
					} else {
						mLoadingText.setText("正在连接易宝支付平台");
					}
				}
			}
		});
	}

	/**
	 * 发送消息 子线程执行完 发消息给主线程处理
	 * 
	 * @param msgWhat
	 * @param obj
	 */
	private static void sendMessage(int msgWhat, Object obj) {
		Message msg = mHandler.obtainMessage();
		msg.what = msgWhat;
		msg.obj = obj;
		mHandler.sendMessage(msg);
	}

	private void backFromPay() {
		// XXX 退出计费activity 还需要清除缓存
		if (UserInfoManager.isLogin() && FoneUtil.isNetOkWithToast(mContext)) {
			// && (FoneConstants.DO_CHARGE_ACTION == mPayType ||
			// (FoneConstants.DO_VIP_ACTION == mPayType && !UserInfoManager
			// .isVip()))

			L.i(TAG, "用户登录 获取VIP状态");
			new Thread(new Runnable() {

				@Override
				public void run() {
					mFonePayManger.getUserFeeNotif();
					sendMessage(GET_USER_VIP_STATE, null);
				}
			}).start();
		} else {
			L.i(TAG, "用户未登录 退出计费");
			finish();
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.common_title_left_bt:
			webviewGoBack();
			break;
		case R.id.get_token:
			break;
		default:
			break;
		}
	}

	private void shouldLoadUrl(String url) {
		if (FoneUtil.isNetOkWithToast(mContext) && null != url) {
			L.i(TAG, "shouldLoadUrl" + url);
			L.i(TAG, "isDoingFee" + isDoingFee);
			L.i(TAG, "isFirstLoading" + isFirstLoading);
			L.i(TAG, "isFirstQuery" + isFirstQuery);
			if (!isFirstLoading && !isSuccess) {
				loadingView();
			}
			if (url.contains("/st?")) {// 支付宝/微信

				url = PayEngine.formatFeeUrl(mContext, mPayFrom, url, mclid);
				// url +="&comefrom="+mPayFrom;
				if (url.contains("ft=2")) {// 支付宝
					isAliFee = true;
					backFlage = 0;
					aliPay(url);
				} else if (url.contains("ft=9")) {// 微信
					isWxPay = true;
					wxPay(url);
				} else {
					L.i(TAG, "未知url支付类型：" + url);
				}
			} else if (isDoingFee) { 
				if (url.contains("preln?")) {
					Reporter.logVipPage("99999");// 点击加入VIP按钮上报栏目ID
					Reporter.logEvent(Reporter.EventId.POPUP_VIP);
					checkUserLoginState();
				} else if (url.contains(".apk")) {
					// String softurl = FoneUtil
					// .getAbsoluteUrl(host, "", info.url)
					// + "&cipher="
					// + Request.getInstance().getCipher();
					String softurl = url;
					Download download = new Download();
					download.setDownloadIsShowRunningNotification(true);
					download.setDownloadUrl(softurl);
					download.setDownloadFileName("16mm");
					download.setDownloadNotification(FoneThirdPayActivity.this);
					download.setDownloadIsInstall(true);
					download.setDownloadIsErrorToast(true);
					download.setDownloadIsLimitSpeed(false);
					download.setDownloadType(Download.DOWNLOAD_RECOMMEND);
					StorageModule.getInstance().addFileDownload(download);
					FoneUtil.showToast(FoneThirdPayActivity.this,
							"已经开始下载16mm应用");
					cancelLoading();

				} else {
					L.i(TAG, "情况未知");
				}

			} else { // 易宝 
				if (isFirstRedirect) {
					isFirstRedirect = false;
					isFirstLoading = false;
				} else if (url.contains("redirect/firstpay")) {
					isFirstRedirect = true;
					isFirstLoading = true;
				} else if (!(url.contains("request?") || url.contains("ebp_gp"))) {
					isFirstLoading = false;
				} else {
					isFirstLoading = true;
				}

				if(url.contains("/success?") ||url.contains("/result?")){
					isSuccess = true;
				} else {
					isSuccess = false;
				}
				if(url.contains("/payerror?")){
					isSuccess = false;
					url_goback = true;
					isPayError = true;
					isFirstRedirect = true;
					isFirstLoading = false;
				}else{
					isPayError = false;
				}
				
				loadUrl(url);
			}
		} else {
			L.i(TAG, "url or net error:" + url, "net error");
		}
	}

	private void loadingResultTip(String url) {
		L.i(TAG, "loadingResultTip isFirstQuery"+isFirstQuery);
		if(isFirstQuery && url.contains("/epayquery?")){
			FoneUtil.showToast(getApplicationContext(), "正在等待支付结果");
//			mLoadingText.setText("正在等待易****反馈支付结果");
		}else if(!url.contains("/epayquery?")){
			isFirstQuery = false;
		}
	}

	private void loadUrl(final String url) {
		L.v(TAG, "loadingUrl:", url);
		if (FoneUtil.isNetOkWithToast(mContext)) {
			if (mWebView != null) {
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (mWebView != null) {
							// url =
							mWebView.loadUrl(url);
						}
					}
				}, 500);
			} else {
				L.i(TAG, "mWebView=null>>>loadurl error!");
			}
		} else {
			L.i(TAG, "无网络不加载页面");
		}
	}

	@Override
	protected void onDestroy() {
		L.v(TAG, "onDestroy", "start");
		super.onDestroy();
		if (loginSuccessBr != null) {
			this.unregisterReceiver(loginSuccessBr);
			loginSuccessBr = null;
		}

		if (mWebView != null) {
			mWebView.stopLoading();
			mWebView.clearView();
			mWebView = null;
		}
		CookieManager.getInstance().removeAllCookie();

		System.gc();
		L.v(TAG, "onDestroy", "end");
	}

	private void initLoginSuccessReceiver() {
		if (intentFilter == null) {
			intentFilter = new IntentFilter();
			intentFilter.setPriority(100);
			intentFilter.addAction(FoneConstant.BROADCAST_LOGIN_SUCCESS);
		}

		if (loginSuccessBr == null) {
			loginSuccessBr = new BroadcastReceiver() {

				@Override
				public void onReceive(Context context, Intent intent) {
					L.i(TAG, "login success 从计费跳到登录  登录成功回到计费页面");
					intent.getBooleanExtra("isSend", false);
					mPayType = intent.getIntExtra("type",
							FoneConstants.DO_CHARGE_ACTION);
					mPayFrom = intent.getStringExtra("payfrom");
					mclid = intent.getStringExtra("clid");
					if (mPayType == FoneConstants.DO_VIP_ACTION) {
						if (UserInfoManager.isVip()) {
							backFromPay();
						} else {
							getThirdPayVIP();
						}
					} else if (mPayType == FoneConstants.DO_CHARGE_ACTION) {
						// TODO 请求充值计费策略
						mFeeUrl = PayEngine.getChargeProUrl(mContext);
						// mFeeUrl += "&comefrom="+mPayFrom;
						mFeeUrl = PayEngine.formatFeeUrl(mContext, mPayFrom,
								mFeeUrl, mclid);
						L.i(TAG, "获取充值策略url" + mFeeUrl);
						loadUrl(mFeeUrl);
					}
					L.v(TAG, "initLoginSuccessReceiver", ">>>>>>>> ");
					abortBroadcast();

				}

			};
			L.v(TAG, "initLoginSuccessReceiver", "register >> ");
			this.registerReceiver(loginSuccessBr, intentFilter);
		}
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

	@Override
	public void onReq(BaseReq arg0) {
	}

	@Override
	public void onResp(BaseResp arg0) {
	}

	@Override
	public void onBackPressed() {
		if (isAliFee && backFlage < 0) {
			return;
		} else if (isAliFee) {
			backFlage = 1;
		}
		webviewGoBack();
	}

	private void webviewGoBack() {
		L.i(TAG, "webviewGoBack isAliFee" + isAliFee);
		L.i(TAG, "webviewGoBack backFlag" + backFlage);
		isFirstQuery = false;
		L.i(TAG,"isSuccess",isSuccess );
		if(isSuccess){
			backFromPay();
		}
		isSuccess = false;
		if (url_goback && null != mWebView) {
			if (mWebView.canGoBack()) {
				WebBackForwardList mWebBackForwardList = mWebView
						.copyBackForwardList(); // 判断当前历史列表是否最顶端,其实canGoBack已经判断过
				if (mWebBackForwardList.getCurrentIndex() > 0) { // 获取历史列表
					String historyUrl = mWebBackForwardList.getItemAtIndex(
							mWebBackForwardList.getCurrentIndex() - 1).getUrl(); // 按照自己规则检查是否为可跳转地址
																					// //注意:这里可以根据自己逻辑循环判断,拿到可以跳转的那一个然后webView.goBackOrForward(steps)
					if (historyUrl.contains("ebp_cap")
							|| historyUrl.contains("request")
							|| historyUrl.contains("paytypes")
							|| historyUrl.contains("bank")) {
						mWebView.goBack();// 执行跳转逻辑
						url_goback = true; // webView.goBackOrForward(-1)
						isFirstLoading = false;
					} else {
						mWebView.goBack();// 执行跳转逻辑
						url_goback = false;
						isFirstLoading = false;
					}
				}
			}
		} else {
			backFromPay();
		}
	}

	private class AlPayResltListenerImp implements AlPayResltListener {

		@Override
		public void onDismiss() {
			L.i(TAG, "is_ali_success" + ali_success);
			if (ali_success) {
				backFromPay();
			}
		}

	}

	private void getThirdPayVIP() {
		// TODO 请求包月策略
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String mVipProtocUrl = PayEngine.getVIPProUrl(mContext);
					// mVipProtocUrl +="&comefrom="+mPayFrom;
					mVipProtocUrl = PayEngine.formatFeeUrl(mContext, mPayFrom,
							mVipProtocUrl, mclid);
					L.i(TAG, "格式化后url" + mVipProtocUrl);
					TelephonyManager tm = (TelephonyManager) ApplicationManage
							.getGlobalContext().getSystemService(
									Context.TELEPHONY_SERVICE);
					String imsi = tm.getSubscriberId();
					if (!(null != imsi && imsi.length() > 0)) {
						mVipProtocUrl += "&type=1";
					}

					L.i(TAG, "无三方" + mVipProtocUrl);
					VIPProtocBean vipProtocBean = PayEngine.getVIPPayProto(
							mVipProtocUrl, null, PayEngine.GET);
					if (null != vipProtocBean) {
						sendMessage(GET_THIRD_PAY_PAGE, vipProtocBean);
					} else {
						FoneUtil.showToast(mContext,
								R.string.retry_network_error);
						L.i(TAG, "请求失败 ");
					}
				} catch (Exception e) {
					e.printStackTrace();
					sendMessage(CANCELLODING, null);
				}

			}
		}).start();

	}

	private void cancelLoading() {
		if (null != mLoading && mLoading.getVisibility() == View.VISIBLE) {
			mLoading.setVisibility(View.GONE);
		}
	}

	private void loadingView() {
		if (null != mLoading && mLoading.getVisibility() != View.VISIBLE) {
			mLoading.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (isWxPay) {
			isWxPay = false;
			cancelLoading();
		}
	}
}
